// stores/production.js
import { defineStore } from 'pinia'
import api from '@/api'

export const useProductionStore = defineStore('production', {
  state: () => ({
    orders: [],
    products: [],
    loading: false,
    currentOrder: null,
    filters: {
      status: '',
      product_id: ''
    }
  }),

  getters: {
    // 获取进行中的订单
    inProgressOrders: (state) => {
      return state.orders.filter(o => o.status === 'IN_PROGRESS')
    }
  },

  actions: {
    // 获取订单列表
    async fetchOrders(filters = {}) {
      this.loading = true
      try {
        const params = { ...this.filters, ...filters }
        const response = await api.get('/production/orders', { params })
        this.orders = response.data
        return response.data
      } catch (error) {
        console.error('获取生产订单失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    // 获取产品列表
    async fetchProducts() {
      this.loading = true
      try {
        const response = await api.get('/production/products')
        this.products = response.data
        return response.data
      } catch (error) {
        console.error('获取产品列表失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    // 创建新订单
    async createOrder(orderData) {
      try {
        const response = await api.post('/production/orders', orderData)
        // 添加到订单列表
        this.orders.unshift(response.data)
        return response.data
      } catch (error) {
        console.error('创建生产订单失败:', error)
        throw error
      }
    },

    // 获取订单详情
    async fetchOrderDetail(orderId) {
      try {
        const response = await api.get(`/production/orders/${orderId}`)
        this.currentOrder = response.data
        return response.data
      } catch (error) {
        console.error('获取订单详情失败:', error)
        throw error
      }
    },

    // 更新订单状态
    async updateOrderStatus(orderId, status) {
      try {
        const response = await api.put(`/production/orders/${orderId}/status`, { status })
        // 更新订单列表中的状态
        const orderIndex = this.orders.findIndex(o => o.id === orderId)
        if (orderIndex !== -1) {
          this.orders[orderIndex] = response.data
        }
        // 如果当前查看的是这个订单，也更新当前订单
        if (this.currentOrder && this.currentOrder.id === orderId) {
          this.currentOrder = response.data
        }
        return response.data
      } catch (error) {
        console.error('更新订单状态失败:', error)
        throw error
      }
    }
  }
})